package com.wrupple.muba.catalogs.client.view.impl;

import java.util.Collection;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.wrupple.muba.catalogs.client.module.services.logic.CatalogDescriptionService;
import com.wrupple.muba.catalogs.client.view.CatalogExportView;
import com.wrupple.muba.catalogs.domain.CatalogEntry;
import com.wrupple.muba.common.client.application.DataCallback;
import com.wrupple.muba.common.shared.StateTransition;
import com.wrupple.muba.common.shared.services.CSVWriter;
import com.wrupple.vegetate.domain.CatalogDescriptor;

public class CatalogExportViewImpl extends Composite implements CatalogExportView {

	private static CatalogExportViewImplUiBinder uiBinder = GWT.create(CatalogExportViewImplUiBinder.class);

	interface CatalogExportViewImplUiBinder extends UiBinder<Widget, CatalogExportViewImpl> {
	}

	class ParseAndShow extends DataCallback<CatalogDescriptor> {
		List<CatalogEntry> parameter;

		public ParseAndShow(List<CatalogEntry> parameter) {
			super();
			this.parameter = parameter;
		}

		@Override
		public void execute() {
			Collection<String> fieldset = result.getFieldNames();
			String csv = presenter.parseEntryFieldsToCSV(fieldset, parameter);
			textArea.setText(csv);
		}

	}

	private CatalogDescriptionService catalogDescriptor;
	private CSVWriter presenter;
	@UiField
	TextArea textArea;
	private StateTransition<Void> callback;

	@Inject
	public CatalogExportViewImpl(CatalogDescriptionService catalogDescriptor,CSVWriter csvutil) {
		initWidget(uiBinder.createAndBindUi(this));
		this.presenter=csvutil;
		this.catalogDescriptor = catalogDescriptor;
	}

	@Override
	public void start(List<CatalogEntry> parameter, StateTransition<Void> onDone,EventBus bus) {
		if (parameter == null || parameter.isEmpty()) {

		} else {
			String catalog = parameter.get(0).getCatalog();
			DataCallback<CatalogDescriptor> parseAndShowCSV = new ParseAndShow(parameter);
			catalogDescriptor.loadCatalogDescriptor(catalog, parseAndShowCSV);
		}
		this.callback = onDone;
	}


	@UiHandler("ok")
	public void ok(ClickEvent e) {
		callback.execute();
	}


}
